/* global Prism */
import Prism from 'prismjs';

import * as React from 'react';
import copy from 'copy-to-clipboard';
import { Icon } from '../components/Icon';
import { CodeBlock } from './CodeBlock';

Prism.languages.markdoc = {
  tag: {
    pattern: /{%(.|\n)*?%}/i,
    inside: {
      tagType: {
        pattern: /^({%\s*\/?)(\w|-)*\b/i,
        lookbehind: true,
      },
      id: /#(\w|-)*\b/,
      string: /".*?"/,
      equals: /=/,
      number: /\b\d+\b/i,
      variable: {
        pattern: /\$[\w.]+/i,
        inside: {
          punctuation: /\./i,
        },
      },
      function: /\b\w+(?=\()/,
      punctuation: /({%|\/?%})/i,
      boolean: /false|true/,
    },
  },
  variable: {
    pattern: /\$\w+/i,
  },
  function: {
    pattern: /\b\w+(?=\()/i,
  },
};

export function Code({
  children,
  title,
  showLanguage = true,
  type,
  url,
}) {
  const [copied, setCopied] = React.useState(false);
  const ref = React.useRef(null);
  const [selectLanguage, setSelectLanguage] = React.useState('curl');
  const languages = ['cURL', 'JavaScript', 'Java'];
  const handleChange = (event) => {
    setSelectLanguage(event.target.value);
  };

  const getCode = () => {
    children = React.Children.toArray(children);
    return children.find(
      (child) => child.props.language === selectLanguage.toLowerCase()
    );
  };

  const codeBlock = getCode();

  const handleCopyClick = () => {
    navigator.clipboard
      .writeText(codeBlock.props.children.props.children)
      .then(() => {
        alert('复制成功');
        console.log('内容已复制到剪贴板');
      })
      .catch((err) => {
        alert('复制失败');
        console.error('复制失败:', err);
      });
  };

  React.useEffect(() => {
    if (ref.current) Prism.highlightElement(ref.current, false);
  }, [children]);

  React.useEffect(() => {
    if (copied) {
      copy(ref.current.innerText);
      const to = setTimeout(setCopied, 1000, false);
      return () => clearTimeout(to);
    }
  }, [copied]);

  // const lang = language === 'md' ? 'markdoc' : language || 'markdoc';
  // const lines =
  //   typeof children === 'string' ? children.split('\n').filter(Boolean) : [];

  return (
    <div className="code" aria-live="polite">
      <div className="code-header">
        <div className="code-header-content">
          <span className="code-title">{title}</span>
          <span className="code-type">{type}</span>
          <span>{url}</span>
        </div>
        <div className="code-operate">
          <select
            value={selectLanguage}
            onChange={handleChange}
            className="select-language"
          >
            {languages.map((language, index) => (
              <option key={index} value={language}>
                {language}
              </option>
            ))}
          </select>
          <Icon
            icon="copy"
            color="var(--color-white)"
            style={{
              cursor: 'pointer',
              width: '16px',
              height: '16px',
            }}
            onClick={handleCopyClick}
          ></Icon>
        </div>
      </div>
      {/* <pre
        // Prevents "Failed to execute 'removeChild' on 'Node'" error
        // https://stackoverflow.com/questions/54880669/react-domexception-failed-to-execute-removechild-on-node-the-node-to-be-re
        key={children}
        ref={ref}
        className={`language-${lang}`}
      >
      </pre> */}
      {
        <CodeBlock
          language={
            codeBlock.props.language === 'curl'
              ? 'javascript'
              : codeBlock.props.language
          }
        >
          {codeBlock.props.children.props.children}
        </CodeBlock>
      }
      <style jsx>
        {`
          .code {
            position: relative;
            border-radius: 8px;
            display: flex;
            flex-direction: column;
          }
          .code-header {
            background-color: #505865;
            color: #fff;
            padding: 8px 12px;
            border-top-left-radius: 4px;
            border-top-right-radius: 4px;
            display: flex;
            justify-content: space-between;
            align-items: center;
          }
          .code-header-content {
            display: flex;
            gap: 12px;
            font-size:15px;
          }
          .code-title {
            display: ${title ? '' : 'none'};
          }
          .code-type {
            color: ${type === 'GET'
              ? 'var(--color-blue-5)'
              : type === 'POST'
              ? 'var(--color-green-5)'
              : type === 'DELETE'
              ? 'var(--color-red-5)'
              : 'var(--color-white)'};
          }
          .code-operate {
            display: flex;
            align-items: center;
            gap: 8px;
          }
          .select-language {
            background-color: #2b3039;
            color: white;
            font-size: 11px;
            width: 80px;
            height: 24px;
            padding: 4px;
            display: ${showLanguage ? '' : 'none'};
          }
          .code pre {
            border-bottom-left-radius: 4px;
            border-bottom-right-radius: 4px;
          }
        `}
      </style>
    </div>
  );
}
